// pages/editPhoto/editPhoto.js
import {
  observer
} from '../../libs/observer';
import { proxy, reqHeader, stringify, ossuploadurl } from '../../utils/util.js';
import Store from './store.js';
import UploadStore from '../community/upload/store.js';
import ContestStore from '../community/contestStore.js';
import LoginStore from '../login/store.js';
const app = getApp();

Page(observer({
  props: {
    store: Store
  },

  /**
   * 页面的初始数据
   */
  data: {
    navbarData: {
      showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
      title: '', //导航栏 中间的标题
      background: 'linear-gradient(to bottom, rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0))',
      hasFilter: true,
      color: '#FFFFFF',
      btnStyle: 'white', //black, white
    },
    navBarHeight: app.globalData.height,
    files:[],
    groupPhoto: false,
    titleValue:'',
    descValue:'',
  },

  uploadFun: function (names) {
    let me = this;
    wx.request({
      url: `${proxy}/community/v2/upload/ossInfo`,
      data: {
        access_token: LoginStore.userInfo.access_token,
        originalNames: JSON.stringify(names),
        uploadType: 'photo'
      },
      header: reqHeader,
      success: function (res) {
        if (res.statusCode != 200) {
          return;
        }
        res = res.data;
        if (res.status == 200) {
          res.data.forEach((_item, _index) => {
            me.uploadImage({
              item: _item,
              index: _index,
              ossInfo: res.ossInfo,
              filePath: _item.fileName,
              ossId: _item.ossId
            })

          });
        } else {
          console.log(res.message);
        }
      }
    })
  },
  uploadImage(params) {
    let me = this;

    wx.getImageInfo({
      src: params.filePath,
      success: function (imgInfo) {
        let _index = params.index;
        var ossInfo = params.ossInfo;

        wx.uploadFile({
          url: ossInfo.host,
          filePath: params.filePath,
          name: 'file', //必须填file
          formData: {
            'key': params.ossId,
            'policy': ossInfo.policy,
            'OSSAccessKeyId': ossInfo.accessid,
            'signature': ossInfo.signature,
            'success_action_status': '200',
          },
          success: function (res) {
            if (res.statusCode != 200) {
              console.log(new Error('上传错误:' + JSON.stringify(res)))
              return;
            }
            console.log('上传图片成功', res);
            wx.request({
              url: `${proxy}/community/v2/photo/save`,
              method: 'POST',
              data: {
                jsonData: stringify([Object.assign({
                  width: imgInfo.width,
                  height: imgInfo.height,
                  "extraInfo": [],
                  "extendedField": {
                    waterMark: 'sw'
                  }, //任意数据都可插入
                  "openState": "profile", //公开状态
                  "title": Store.titleValue, //组图标题
                  "description": Store.descValue, //组图描述
                  "tags": "", //关键词
                  "categoryId": "0", //分类
                  "doTsa": false
                }, params.item)]),
                access_token: LoginStore.userInfo.access_token
              },
              header: Object.assign({
                'content-type': 'application/x-www-form-urlencoded'
              }, reqHeader),
              success: function (_res) {
                wx.hideLoading();
                if (_res.statusCode != 200) {
                  return;
                }

                _res = _res.data;
                if (_res.status == 200){
                  wx.redirectTo({
                    url: `/pages/userInfo/userInfo?userId=${LoginStore.userInfo.userId}`,
                  })
                }else{
                  console.log(_res.message);
                }
              }
            })
          },
          fail: function (err) {
            console.log(err)
          },
        })

      }
    })


  },

  uploadWorks:function(){
    if (this.data.options && this.data.options.filePath){
      // 单图上传
      wx.showLoading({
        title: '上传中...',
        mask:true
      })
      this.uploadFun([this.data.options.filePath]);
      
    }else{
      if (this.data.files.length > 1 && !Store.titleValue){
        wx.showModal({
          title: '提示',
          content: '请为作品设置标题哦！',
          showCancel:false
        });
        return;
      }
      wx.redirectTo({
        url: '/pages/community/upload/upload'
      }); 
    }
    
  },
  inputTitle:function(e){
    Store.setTitle(e.detail.value)
  },
  inputDesc:function(e){
    Store.setdesc(e.detail.value)
  },
  deletePhoto:function(e){
    let index = e.currentTarget.dataset.position;
    let photoList = [...this.data.files];
    let curPath = photoList[index].path;
    photoList.splice(index, 1);
    if (curPath === Store.coverPath) {
      Store.setCover(photoList[0].path);
    }
    this.setData({
      files: photoList
    },()=>{
      UploadStore.UpdateFilePath(photoList);
    })
    if (photoList.length == 1) {
      Store.setCover("");
    }
  },
  addPhoto:function(){
    ContestStore.takePhoto((path)=>{
      let addPhotoList = [];
      path.forEach((item, index) => {
        addPhotoList.push({
          path: item
        });
        
      });
      addPhotoList = this.data.files.concat(addPhotoList);
      
      if (!Store.coverPath){
        Store.setCover(addPhotoList[0].path);
      }
      this.setData({
        files: addPhotoList
      },()=>{
        UploadStore.UpdateFilePath(addPhotoList);
        console.log(this.data.files);
      })
    },true)
  },
  showBlackPage:function(e){
    let selectedNum = e.currentTarget.dataset.num;
    let files = this.data.files;
    let resourceType = 0;
    let photoList = files[0].path;
    if(files.length>1){
      resourceType = 2;
      photoList = '';
      for (let item of files) {
        photoList += `${item.path},`
      }
    }
    
    wx.navigateTo({
      url: `/pages/groupFull/groupFull?photoList=${photoList}&resourceType=${resourceType}&selectedNum=${selectedNum}`,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    // debugger;
    Store.reset();
    let me = this;
    if (options.filePath){
      this.setData({
        options: options,
        files: [{ path: options.filePath}]
      })
    }else{
      let filesData = [];
      UploadStore.filePaths.forEach((item, index) => {
        console.log(item);
        if (typeof item === 'string'){
          let pathdata = {}
          pathdata.path = item;
          filesData[index] = pathdata;
        }else{
          filesData[index] = item;
        }
      });
      this.setData({
        files: filesData,
        // groupPhoto: ContestStore.groupPhoto
        groupPhoto: true
      });
      if (filesData.length>1){
        Store.setCover(filesData[0].path);
        let descObj = {};
        for (let item of filesData){
          descObj[item.path] = '';
        }
        Store.initDescObj(descObj);
      }
    }
    console.log(UploadStore.filePaths);
    console.log(this.data.files);
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // }
}))